import numpy as np
import requests
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FuncFormatter
import matplotlib as mpl
import matplotlib.dates as mdate
import matplotlib.ticker as mtick
import time

# plt.figure(1) # 创建图表1
# plt.figure(2) # 创建图表2
# ax1 = plt.subplot(211) # 在图表2中创建子图1
# ax2 = plt.subplot(212) # 在图表2中创建子图2
# x = np.linspace(0, 3, 100)
# for i in range(5):
#     plt.figure(1)  # 选择图表1
#     plt.plot(x, np.exp(i*x/3))
#     plt.sca(ax1)   # 选择图表2的子图1
#     plt.plot(x, np.sin(i*x))
#     plt.sca(ax2)  # 选择图表2的子图2
#     plt.plot(x, np.cos(i*x))
# plt.show()
# 乐视网
# data_url = 'http://market.finance.sina.com.cn/downxls.php?date=2017-04-05&symbol=sz000538'
# 莱克电气
# data_url = 'http://market.finance.sina.com.cn/downxls.php?date=2017-03-01&symbol=sh603355'
# 一汽夏利
# data_url = 'http://market.finance.sina.com.cn/downxls.php?date=2017-04-05&symbol=sz000927'
# 北方导航
data_url = 'http://market.finance.sina.com.cn/downxls.php?date=2017-04-10&symbol=sh600435'
r = requests.get(data_url, stream=True)
content = r.content.decode('gbk')
f = open("300104.cvs", "wb+")
f.write(content.encode())
f.close()
f = open("300104.cvs", "r", encoding='UTF-8')
# 成交时间0	成交价1	价格变动2	 成交量(手)3	成交额(元)4	性质5
last_close = 0
skip_head = 0
times = []
prices = []
rise_rate = []
buy_vol = []
sell_vol = []
pan_vol = []
buy_money = []
sell_money = []
pan_money = []
net_buy_money = []
x_array = []
x = 0
count = 0
price2 = 0
price_change2 = 0
buy_v = 0
sell_v = 0
buy_m = 0
sell_m = 0
group_size = 20 * 5
for eachLine in f:
    line = eachLine.split()
    if skip_head == 0:
        skip_head = 1
        continue
    # count -= 1
    # if count == 0:
    #     break

    count += 1
    x += 1

    time_str = line[0]
    price = float(line[1])
    price_change = float(line[2].replace('--', '0'))
    vol = float(line[3])
    money = float(line[4])
    prop = line[5]

    if prop == '买盘' or (prop == '中性盘' and price_change >= 0):
        buy_v += vol
        buy_m += money

        # print(prop)
    elif prop == '卖盘' or (prop == '中性盘' and price_change < 0):
        sell_v += vol
        sell_m += money
    else:
        print('中性盘' + str(vol))
    if group_size == count:
        count = 0
        x_array.append(x)
        buy_vol.append(buy_v)
        buy_money.append(buy_m)
        sell_vol.append(sell_v)
        sell_money.append(sell_m)
        times.append(time_str)  # time.strptime(time_str, '%H:%M:%S')
        prices.append(price)
        net_buy_money.append((buy_m - sell_m) / 10000000)

f.close()
print(len(rise_rate))
print(len(x_array))
print(len(prices))
times.reverse()
prices.reverse()
rise_rate.reverse()
buy_vol.reverse()
buy_money.reverse()
sell_vol.reverse()
sell_money.reverse()
net_buy_money.reverse()
last_close = prices[0]
for price in prices:
    rise_rate.append((price - last_close) / last_close * 100)
plt.figure(1)  # 创建图表1
mpl.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
mpl.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
ax1 = plt.subplot(111)
# plt.plot(x_array, buy_money)
ax1.set_title("净买入与涨幅")
plt.plot(x_array, net_buy_money, 'r', label='净买入金额（千万）')
ax1.set_ylabel('净买入金额（千万）')
axis = plt.gca().xaxis
# axis.set_major_locator(mdate.DateFormatter('%H:%M:%S'))
plt.xticks(x_array, times)
for label in axis.get_ticklabels():
    label.set_color("black")
    label.set_rotation(45)
    label.set_fontsize(10)

# 设置双坐标轴，右侧Y轴
ax2 = ax1.twinx()

# 设置右侧Y轴显示百分数
# fmt = '%.2f%%'
# yticks = mtick.FormatStrFormatter(fmt)

# 绘制成功率图像
# ax2.set_ylim(-3, 3)
ax2.plot(x_array, rise_rate, 'b', label='涨幅（%）')
ax2.set_ylabel('涨幅（%）')
# ax2.plot(price)
# ax2.yaxis.set_major_formatter(yticks)
# legend1 = ax1.legend(loc=(.02, .94), fontsize=16, shadow=True)
# legend2 = ax2.legend(loc=(.02, .9), fontsize=16, shadow=True)
# legend1.get_frame().set_facecolor('#FFFFFF')
# legend2.get_frame().set_facecolor('#FFFFFF')
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
# plt.legend()
plt.show()
